<template>
  <div class="select" :class="{'black':block}">
    <div @click="showAction">
      <slot v-bind:code="code" v-bind:label="label"></slot>
    </div>
    <vant-action-sheet 
    v-model="show" 
    :title="title" 
    :actions="actions" 
    v-bind="$attrs"
    @select="onSelect" />
  </div>
</template>

<script>
export default {
  props: {
    title: {
      type: String,
      default: ''
    },
    list: {
      type: Array,
      default() {
        return []
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    block: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    },

  },
  data() {
    return {
      show: this.visible,
      code: '',
      label: '请选择',
      actions: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        this.code = v;
        if (v && this.actions.length) {
          const label = this.actions.find(item => item.code === v);
          this.label = label ? label.name : '';
        }
      }
    },
    list: {
      immediate: true,
      handler(v) {
        this.actions = v;

        const { code } = this;
        if (code && v.length) {
          const label = v.find(item => item.code === code);
          this.label = label ? label.name : ''
        }
      }
    },
    visible(v) {
      this.show = v
    },
    show(v, olv) {
      if (v !== olv) {
        this.$emit('update:visible', v)
      }
    }
  },
  methods: {
    onCancel() {
    },
    showAction() {
      this.show = true
    },
    onSelect(item = {}) {
      const { name = '', code = '' } = item
      this.code = code
      this.label = name
      this.show = false;

      this.$emit('input', code);
      this.$emit('change', item);
      this.actions.forEach(action => {
        if (action.code === code) {
          //  action.className='active'
          this.$set(action, 'className', 'active')
        } else if (action.className && action.className.includes('active')) {
          const className = action.className.replace(/\bactive\b/, '');
          this.$set(action, 'className', className)
        }
      })
      
    }
  }
}
</script>

<style lang="less" scoped>
.select {
  display: inline-block;
  vertical-align: top;
  &.black {
    display: block;
  }
  .active {
    color: @c-red;
  }
}
</style>